package com.lianboke.link.ad.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lianboke.link.ad.R;
import com.lianboke.link.ad.Views.FullyLinearLayoutManager;
import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.adapter.AccountAdapter;
import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.beans.OrderShiPinTaskModel;
import com.lianboke.link.ad.beans.ShiPinBean;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.updateUtils.AppUtils;
import com.lianboke.link.ad.updateUtils.DownloadAppManager;
import com.lianboke.link.ad.utils.DateUtil;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 互助任务中的互粉接口
 */
public class OrderTypeDetailsForHuZhuByFansActivity extends BaseActivity {

    @BindView(R.id.tv_join_order_name_content_h)
    public TextView tv_join_order_name_content_h;

    @BindView(R.id.tv_join_time_content_h)
    public TextView tv_join_time_content_h;

    @BindView(R.id.tv_join_device_content_h)
    public TextView tv_join_device_content_h;

    @BindView(R.id.tv_join_jingling_account_h)
    public TextView tv_join_jingling_account_h;

    @BindView(R.id.tv_join_jingling_pwd_h)
    public TextView tv_join_jingling_pwd_h;

    @BindView(R.id.tv_join_down_h)
    public TextView tv_join_down_h;

    @BindView(R.id.et_join_account_content_h)
    public EditText et_join_account_content_h;



    @BindView(R.id.rv_account_h)
    public RecyclerView rv_account_h;

    @BindView(R.id.btn_join_cancle_h)
    public Button btn_join_cancle_h;

    @BindView(R.id.btn_join_submit_h)
    public Button btn_join_submit_h;

    @BindView(R.id.loading_progress)
    public ProgressBar loading_progress;

    private boolean iHasInstall = false;//是否已安装


    //数据展示
    private List<ShiPinBean> listAccountDatas = new ArrayList<ShiPinBean>();


    //粉丝数据
    private AccountAdapter accountAdapter;//账号适配器

    private long lTaskId;//任务id
    private String  strOrderName;//任务名称

    private String strUserid;
    private String strAppPackageName;
    private String strAppUrl;//下载地址

    //可取消的观察者
    private Disposable mDisposable;//可以取消观察者
    @Override
    public int getContentViewId() {
        return R.layout.activity_order_type_details_for_hu_zhu_by_fans;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {
        setTitleBackShow(true);
        setTitleContent("互助详情任务附属页");

        lTaskId = getIntent().getLongExtra("order_id",0);
        strOrderName = getIntent().getStringExtra("order_name");

        tv_join_order_name_content_h.setText(strOrderName);
        //获取当前系统时间
        String strTime = DateUtil.getCurDateStr();
        tv_join_time_content_h.setText(strTime);

        //设备号
        String strDeviceNum = DeviceUtils.getImei(actContext);
        tv_join_device_content_h.setText(strDeviceNum);

        //取消
        btn_join_cancle_h.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //提交任务资料
        btn_join_submit_h.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(iHasInstall){
                    //提交互助账号信息
                    uploadOrderTaskImgs();
                }else{
                    //未安装
                    shouInstallDialog();
                }

            }
        });
        rv_account_h.setLayoutManager(new FullyLinearLayoutManager(this));
        accountAdapter = new AccountAdapter(actContext);
        rv_account_h.setAdapter(accountAdapter);
        rv_account_h.setNestedScrollingEnabled(false);
        DownloadAppManager.initDownLoadManager(actContext);
        showLoadingProgress();
        //获取视频互粉任务
        getShipinAccountDetails();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        DownloadAppManager.initDownLoadManager(actContext).destoryDownLoadService();
        if(mDisposable!=null && !mDisposable.isDisposed()){
            mDisposable.dispose();
        }
    }

    @Override
    public boolean initLocalBroadcastReceiver() {
        return true;
    }

    /**
     * 显示卸载对画框
     */
    public void shouInstallDialog(){
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请安装按键精灵")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        downloadInstallAppInfo(strAppUrl);
                    }
                })
                .create().show();
    }

    /**
     * 获取互相关注信息
     */
    public void getShipinAccountDetails(){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("taskid", String.valueOf(lTaskId));
        params.put("deviceid", DeviceUtils.getImei(actContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);

        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_TYPE_ORDER_HUZHU_FANS, params, new HttpCallBack<OrderShiPinTaskModel>() {
            @Override
            public void onSuccess(OrderShiPinTaskModel data) {
                hideLoadingProgress();
                if(data==null){
                    ToastUtil.show(actContext,"获取粉丝接口失败!", Toast.LENGTH_LONG);
                }else {
                    //解析信息
                    setOrderShipinTaskDetailsInfo(data);
                }
            }

            @Override
            public void onFail(String msg) {
                hideLoadingProgress();
                if(TextUtils.isEmpty(msg)){
                    msg = "获取粉丝接口失败!";
                }
                ToastUtil.showShort(actContext,msg);
            }
        });
    }

    /**
     * 解析视频信息
     */
    public void  setOrderShipinTaskDetailsInfo(OrderShiPinTaskModel data){
        if(data!= null){
            listAccountDatas = data.getList();
            tv_join_jingling_account_h.setText("账号: "+data.getAnjianusername());
            tv_join_jingling_pwd_h.setText("密码: "+data.getAnjianpassword());
            strAppPackageName = data.getAnjianname();
            strAppUrl = data.getAnjiandownload();
            if(AppUtils.hasApp(actContext,strAppPackageName)){
                //已经安装相应的app
                tv_join_down_h.setText("已安装按键精灵 ");
                iHasInstall = true;
            }else{
                tv_join_down_h.setText(" 未安装按键精灵");
                iHasInstall = false;
            }
            //刷新账号信息
            accountAdapter.refresh(listAccountDatas);
        }
    }

    /**
     * 批量提交图片
     */
    public void uploadOrderTaskImgs(){
        strUserid = et_join_account_content_h.getText().toString();
        if(TextUtils.isEmpty(strUserid)){
            ToastUtil.show(actContext,"请填写账号信息", Toast.LENGTH_LONG);
            return;
        }
        submitOrderTaskInfo();
    }

    /**
     * 提交信息
     */
    public void submitOrderTaskInfo(){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("account",strUserid);
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("taskid",String.valueOf(lTaskId));
        params.put("deviceid", DeviceUtils.getImei(actContext));
        params.put("city", MyApplication.strCity);

        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_ORDER_TASK_SHIPIN_ADD_ACCOUNT, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String datas) {
                hideLoadingProgress();
                ToastUtil.show(actContext,"任务提交成功", Toast.LENGTH_LONG);
                finish();
            }
            @Override
            public void onFail(String msg) {
                hideLoadingProgress();
                ToastUtil.showShort(actContext,msg);
            }
        });
    }

    /**
     * 显示加载框
     */
    private void showLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!= View.VISIBLE){
            loading_progress.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏家在狂
     */
    private void hideLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!=View.GONE){
            loading_progress.setVisibility(View.GONE);
        }
    }
    /**
     * 下载与安装app
     */
    public void downloadInstallAppInfo(String strUrl){
        if(TextUtils.isEmpty(strUrl)){
            ToastUtil.show(actContext,"下载地址错误",Toast.LENGTH_SHORT);
        }else{
            initCustomerLoadingDialog("任务下载中...");
            List<String> datas = new ArrayList<String>();
            datas.add(strUrl);
            MyApplication.appPackNameUrlMap.put("com.cyjh.mobileanjian",strUrl);
            DownloadAppManager.initDownLoadManager(actContext).startDownLoadApp(datas);
        }
    }


    /**
     * 上报任务状态 1 安装、2 卸载、3 启动、4 完成
     * @param status
     * @param packagename (卸载时需要传卸载的packname)
     */
    public void  reportedAppInfo(int status,String packagename){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(appContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);

        if(!strAppPackageName.equals(packagename)){
            params.put("taskid","");
            params.put("appname",packagename);
        }else{
            params.put("taskid",String.valueOf(lTaskId));
            params.put("appname",strAppPackageName);
        }

        params.put("status",String.valueOf(status));
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_TYPE_ORDER_REPORTPROCESS, params, new HttpCallBack<Integer>() {

            @Override
            public void onSuccess(Integer data) {
                if(data!=null && data.intValue()==1){
                    KLog.e("shangbao_log","-------------onSuccess-------------------");
                }
            }

            @Override
            public void onFail(String msg) {
                KLog.e("shangbao_log","-------------onFail-------------------"+msg);
            }
        });
    }
    //===============================接收器======================================

    /**
     * 接受下载的操作
     * @param action
     */
    @Override
    public void getDownLoadMyBroadcastReceiver(String action) {
        KLog.e("-------------getDownLoadMyBroadcastReceiver----------:"+action);
        if(TextUtils.isEmpty(action)){
            return;
        }
        if("android.myapp.download.downloadstart".equals(action)){
            //开始下载指定app
            Long downloadId = MyApplication.appUrlDownIdMap.get(strAppUrl);
            if(downloadId>0){
                setShowAndHideCustomLoadingProgress(true);
                startCheckProgress(downloadId);
            }else{
                setShowAndHideCustomLoadingProgress(false);
            }
        }else if("android.myapp.download.downloadsuccess".equals(action)){
            //下载成功
            setShowAndHideCustomLoadingProgress(false);
            updateCustomerLoadingDialog("安装中...");
            setShowAndHideCustomLoadingProgress(false);
        }else if("android.myapp.download.downloadfails".equals(action) || "android.myapp.download.downloadexecption".equals(action)){
            //下载失败
            MyApplication.appPackNameUrlMap.remove("com.cyjh.mobileanjian");
            closedCustomerLoadingDialog();
            ToastUtil.show(actContext,"任务下载失败，请稍后再试",Toast.LENGTH_SHORT);
        }
    }

    @Override
    public void getInstallMyBroadcastReceiver(String action) {
        //安装
        KLog.e("-------------install----------:"+action);
        if(!TextUtils.isEmpty(action) && strAppPackageName.equals(action) ){
            //关闭等待框
            closedCustomerLoadingDialog();
            //上报状态
            reportedAppInfo(1,strAppPackageName);
            //更新ui
            tv_join_down_h.setText("已安装此任务");
            iHasInstall = true;
        }
    }
    @Override
    public void getReplaceMyBroadcastReceiver(String action) {
        //替换任务
        KLog.e("-------------install----------:"+action);
        if(!TextUtils.isEmpty(action) && strAppPackageName.equals(action) ){
            //关闭等待框
            closedCustomerLoadingDialog();
            //上报状态
            reportedAppInfo(1,strAppPackageName);
            //更新ui
            tv_join_down_h.setText("已安装此任务");
            iHasInstall = true;
        }
    }

    @Override
    public void getRemoveMyBroadcastReceiver(String data) {
        //卸载
        KLog.e("-------------remove----------:"+data);
        if(!TextUtils.isEmpty(data) && strAppPackageName.equals(data) ){
            tv_join_down_h.setText("未安装此任务");
            iHasInstall = false;
            reportedAppInfo(2,strAppPackageName);
        }else if(!TextUtils.isEmpty(data)){
            reportedAppInfo(2,data);
        }
    }

    //================================下载进度=============================
    //开始监听进度
    private void startCheckProgress(long downloadId) {
        Observable
                .interval(1, 10, TimeUnit.MILLISECONDS, Schedulers.io())//无限轮询,准备查询进度,在io线程执行
                .filter(times -> DownloadAppManager.initDownLoadManager(actContext).mDownloadBinder != null)
                .map(i -> DownloadAppManager.initDownLoadManager(actContext).mDownloadBinder.getProgress(downloadId))//获得下载进度
                .takeUntil(progress -> progress >= 100)//返回true就停止了,当进度>=100就是下载完成了
                .distinct()//去重复
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressObserver());
    }


    //观察者
    private class ProgressObserver implements Observer<Integer> {

        @Override
        public void onSubscribe(Disposable d) {
            mDisposable = d;
        }

        @Override
        public void onNext(Integer progress) {
            setCustomLoadingDialogProgressValue(progress);
        }

        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
            setShowAndHideCustomLoadingProgress(false);
            ToastUtil.showShort(actContext,"监控下载进度失败！");
        }

        @Override
        public void onComplete() {
            setCustomLoadingDialogProgressValue(100);
        }
    }
    //=============================开始启动自动任务============================
    @Override
    public void getTimerOrderdMyBroadcastReceiver(String action) {
        KLog.e("----------getTimerOrderdMyBroadcastReceiver-----------:" + action);
        if ("android.myapp.timer.orders.auto.start".equals(action)) {
            //结束本页面
            finish();
        }
    }
}
